/* Cobber create 2024-07-19 */

const { v4: uuid } = require('uuid');
const amqp = require('amqplib/callback_api');
const { RABBIT_HOST, RABBIT_EX, RABBIT_QUEUE } = require('../config/rabbit.config');

const cluster = require('child_process');



// function apic() {
//     return new Promise((resolve) => {
//         setTimeout(() => {
//             resolve('hello world')
//         }, 100)
//     })
// }


async function consume() {
    // qps
    // 20 qps 50ms
    let qps_count = 5; // 计数器
    let instanceId = null; // 加入的key
    const queue = []; // 队列
    const qps_slot = []; // 队列槽位
    const qps_intance = {}; // 队列实例

    const worker = cluster.fork('./rabbitmq/worker.js');
    // TODO 这里调不通，需要研究一下
    worker.on('message', async data => {
        console.log('Received message from worker', data)
        // 核销 ack
        
    })
    // amqplib.connect(RABBIT_HOST, (err, conn) => {
    //     if (err) {
    //       console.error('Could not connect to RabbitMQ', err)
    //       return
    //     }
    //     conn.createChannel((err, ch) => {
    //       if (err) {
    //         console.error('Could not create channel', err)
    //         return
    //       }
    //       ch.assertQueue(RABBIT_QUEUE, { durable: true }, (err, q) => {
    //         if (err) {
    //           console.error('Could not assert queue', err)
    //           return
    //         }
    //         console.log('Waiting for messages in %s. To exit press CTRL+C', RABBIT_QUEUE)
    //         ch.prefetch(4)
    //         ch.consume(RABBIT_QUEUE, (msg) => {
    //             const payload = msg.content.toString()
    //             console.log('Received message', payload.includes('{') ? JSON.parse(payload) : payload)
    //             ch.ack(msg)
    //         }, { noAck: false })
    //       })
    //     })
    //     conn.on('error', (err) => {
    //       console.error('RabbitMQ connection error', err)
    //       consume(host)
    //     })
    // })

    while (true) {
        try {
            const key = new Date().getMilliseconds()
            if (key % Math.floor(1000/qps_count) === 0 && Math.abs(key - instanceId) > Math.floor(1000/qps_count*0.9)) {
                if (qps_slot.length >= qps_count) {
                    const qps_id = qps_slot.shift();
                    if (qps_intance[qps_id]) delete qps_intance[qps_id]
                    else delete qps_intance[Object.keys(qps_intance)[0]]
                }
                if(!qps_slot.includes(key)) {
                    instanceId = key;
                    qps_slot.push(key);
                } 
            }
            
        
            // channel.consume(RABBIT_QUEUE, (msg) => {
            //   console.log(`Received message: ${msg.content.toString()}`);
            // }, { noAck: true });
            // console.log(Object.keys(qps_intance).length, qps_count)
            if (qps_slot.length && !qps_intance[instanceId] && Object.keys(qps_intance).length < qps_count) {
                // 向队列请求数据
                if (!queue.length) queue.push(...[{id: uuid(), type: 1, data: 'hello'}, {id: uuid(), type: 1, data: 'world'}, {id: uuid(), data: 'qps'}]);
                
                const unshift_queue = queue.shift();
                if (unshift_queue.type === 1) {
                    worker.send(unshift_queue) // 发送到子进程
                    qps_intance[instanceId] = unshift_queue
                }
                // console.log(qps_intance)
            }
            
        } catch (error) {
            console.error(error);
        }
    }
  
}

consume();
// apic();